import json
import threading

import requests  # 配置北向用户信息及北向地址nbi_name = "campus02@north.com"
from urllib3.exceptions import InsecureRequestWarning


class Token:
    _instance_lock = threading.Lock()

    def __new__(cls, *args, **kwargs):
        if not hasattr(Token, "_instance"):
            with Token._instance_lock:
                if not hasattr(Token, "_instance"):
                    Token._instance = object.__new__(cls)
        return Token._instance

    def __init__(self):
        self.grantType = "password"
        self.userName = "19859215991"
        self.value = "dnf00gg.com"
        self.host = "117.78.31.209"
        self.port = "26335"
        # 定义接口的 URI
        self.PUT_TOKEN_URL = "/rest/plat/smapp/v1/oauth/token"
        # 配置 URL 和 Headers
        self.post_token_url = "https://" + self.host + ":" + self.port + self.PUT_TOKEN_URL
        self.headers_post = {'Content-Type': 'application/json', 'Accept': 'application/json'}
        self.tokenNow = self.get_token()
        # print(self.r.json(), self.tokenNow)

    def __int__(self, nbi_pwd, nbi_name, host, port, POST_TOKEN_URL, post_token_url, headers_post):
        pass

    def get_token(self):
        requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
        tmp = {"grantType": "password", "userName": self.userName, "value": self.value}
        # 发起请求，添加 Json 格式数据
        self.r = requests.put(self.post_token_url, headers=self.headers_post,
                              data=json.dumps(tmp), verify=False)
        # 解析 token_id
        # print(self.r)
        token_id = self.r.json()['accessSession']
        return token_id


if __name__ == '__main__':
    Token()
